import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../license_page/model/license.dart';
import '../license_page/widget/license_widget.dart';

class LicensesRegistryPage extends StatelessWidget {
  const LicensesRegistryPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: const Text('Licenses'),
          centerTitle: true,
        ),
        body: FutureBuilder<List<License>>(
          future: loadLicenses(),
          builder: (context, snapshot) {
            final licenses = snapshot.data;

            switch (snapshot.connectionState) {
              case ConnectionState.waiting:
                return const Center(child: CircularProgressIndicator());
              default:
                if (snapshot.hasError) {
                  return const Center(child: Text('Some error occurred!'));
                } else {
                  return LicenseWidget(licenses: licenses!);
                }
            }
          },
        ),
      );

  Future<List<License>> loadLicenses() async =>
    LicenseRegistry.licenses.asyncMap<License>((license) async {
      final title = license.packages.join('\n');
      final text = license.paragraphs
          .map<String>((paragraph) => paragraph.text)
          .join('\n\n');
      return License(title, text);
    }).toList();
}